﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace FortuneArterial.Site.Laboratory
{
    public class BaseController
        : Controller
    {
        #region 扩展内容

        protected ActionResult SmartView(object model = null)
        {
            if (Request.QueryString.Count > 0 && Request.QueryString[0] == "html")
            {
                //读取View文件内容
                var path = System.IO.Path.Combine(Server.MapPath("~/Views"),
                    this.RouteData.Values["controller"].ToString(),
                    this.RouteData.Values["action"].ToString() + ".cshtml");
                var content = System.IO.File.ReadAllText(path);

                return Content(HttpUtility.HtmlEncode(content));
            }
            else if (Request.QueryString.Count > 0 && Request.QueryString[0] == "cs")
            {
                //反射获取Action的主体
                var action = (from t in Assembly.GetExecutingAssembly().GetTypes()
                              where t.Name == this.RouteData.Values["controller"].ToString() + "Controller"
                              select t.GetMethod(this.RouteData.Values["action"].ToString()))
                              .FirstOrDefault<MethodInfo>();

                var method = Encoding.Default.GetString(action.GetMethodBody().GetILAsByteArray());
                return Content(HttpUtility.HtmlEncode(method));
            }
            else {
                if (Request.IsAjaxRequest())
                {
                    return PartialView(model);
                }

                return View(model);
            }
        }

        #endregion
    }
}